//
//  CTSecondPageViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/9.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class CTSecondPageViewController: UIViewController {

    var informationArray:NSMutableArray?
    var scanIdImage:UIImage?
    var headerImage:UIImage?
  //  @IBOutlet weak var headerView: UIImageView!
    
    @IBOutlet weak var bottomHeight: NSLayoutConstraint!
    @IBOutlet weak var infoHeight: NSLayoutConstraint!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var headerButton: UIButton!
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var sexLabel: UILabel!
    
    @IBOutlet weak var ageLabel: UILabel!
    
    @IBOutlet weak var idCardLabel: UILabel!
    
    @IBOutlet weak var detailLabel: UILabel!
    
    @IBOutlet weak var idCardImageView: UIImageView!
    
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var infoView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        AipOcrService.shard().auth(withAK: BaiduYunAPIKey, andSK: BaiduYunSecretKey)
        self.infoHeight.constant = 130 * SCREEN_WIDTH/320
        self.bottomHeight.constant = 145 * SCREEN_WIDTH/320
        self.bottomView.isUserInteractionEnabled = true
        self.idCardImageView.isUserInteractionEnabled = true
        let reTap = UITapGestureRecognizer(target: self, action: #selector(reTapClick(_:)))
        self.idCardImageView.addGestureRecognizer(reTap)
        self.setupUIData()
        
        self.infoView.layer.cornerRadius = 5
        self.infoView.layer.masksToBounds = true
        
       self.headerButton.layer.cornerRadius = 52
        self.headerButton.layer.masksToBounds = true
        
        self.idCardImageView.layer.cornerRadius = 5
        self.idCardImageView.layer.masksToBounds = true
        
        self.nextButton.layer.cornerRadius = 5
        self.nextButton.layer.masksToBounds = true
    }
    fileprivate func setupUIData(){
        self.nameLabel.text = self.informationArray?[0] as? String
        self.ageLabel.text = self.informationArray?[1] as? String
        self.idCardLabel.text = self.informationArray?[2] as? String
        self.sexLabel.text = self.informationArray?[3] as? String
        self.detailLabel.text = self.informationArray?[4] as? String
        self.idCardImageView.image = self.scanIdImage
        if (self.headerImage != nil) {
            self.headerButton.setImage(self.headerImage, for: .normal)
        }
    }
    @objc fileprivate func reTapClick(_ tap:UITapGestureRecognizer){
        let ocrVc = AipCaptureCardVC.viewController(with: .localIdCardFont) { (ocrImage) in
            AipOcrService.shard().detectIdCardFront(from: ocrImage, withOptions: nil, successHandler: { (result) in
                
                DispatchQueue.main.async {
                    self.setupResultWithUI(result as! [String : AnyObject])
                    self.idCardImageView.image = ocrImage
                    self.scanIdImage = ocrImage
                    self.dismiss(animated: true, completion: {
                    })
                }
            }, failHandler: { (error) in
                
            })
        }
        
        self.present(ocrVc!, animated: true) {
            
        }
    }
    fileprivate func setupResultWithUI(_ result:[String:AnyObject]){
        self.informationArray = NSMutableArray.init()
        if (result["words_result"] != nil){
            (result["words_result"])?.enumerateKeysAndObjects({ (mykey, myObj, myStop) in
                guard let selectObj : NSDictionary = myObj as? NSDictionary else{
                    return
                }
                if let selectWord = selectObj["words"] {
                    self.informationArray?.add(selectWord)
                }else{
                    return
                }
            })
        }else{
            
        }
        
        let userAge = self.switchDateToAge(self.informationArray![1] as! String)
        self.informationArray?.replaceObject(at: 1, with: userAge)
        self.setupUIData()
    }
    fileprivate func switchDateToAge(_ year:String) -> String{
        
        let formate = DateFormatter()
        formate.dateFormat = "yyyyMMdd"
        let date = formate.date(from: year)
        let currentDate = NSDate()
        let time = currentDate.timeIntervalSince(date!)
        let age = Int(time)/(3600*24*365)
        return String(age)
        
    }
    
    @IBAction func headerButtonClick(_ sender: Any) {
        var responder = self.next
        while !(responder is UIViewController) {
            responder = responder?.next
        }
        if responder is UIViewController {
            let vc = responder as! UIViewController
            
            let tool = PhotoSheet()
            tool.showCTOnlyPhotoSheet(viewController: vc) { [unowned self](images) in
                if images != nil && images!.count > 0 {
                    self.headerImage = images![0]
                    self.headerButton.setImage(images![0], for: UIControlState.normal)
                }
            }
            
        }
    }
    
    @IBAction func nextButtonClick(_ sender: Any) {
        guard  (self.headerImage != nil) else {
            QWTextonlyHud("请拍摄上传您的真实头像!", target: self.view)
            return
        }
        guard let name : String = self.informationArray![0] as? String,name != "" else{
            QWTextonlyHud("姓名不完全,请重新扫描", target: self.view)
            return
        }
        guard let ageLabel : String = self.informationArray![1] as? String,ageLabel != "" else{
            QWTextonlyHud("年龄不完全,请重新扫描", target: self.view)
            return
        }
        guard let idCardLabel : String = self.informationArray![2] as? String,idCardLabel != "" else{
            QWTextonlyHud("身份证不完全,请重新扫描", target: self.view)
            return
        }
        guard let sexLabel : String = self.informationArray![3] as? String,sexLabel != "" else{
            QWTextonlyHud("性别不完全,请重新扫描", target: self.view)
            return
        }
        guard let detailLabel : String = self.informationArray![4] as? String,detailLabel != "" else{
            QWTextonlyHud("地址不完全,请重新扫描", target: self.view)
            return
        }
        let reverse = CTReverseViewController(nibName: "CTReverseViewController", bundle: nil)
        reverse.headerImage = self.headerImage
        reverse.positiveCardImage = self.scanIdImage
        reverse.informationArray = self.informationArray
    self.navigationController?.pushViewController(reverse, animated: true)
    }
}


